<template>
  <div>
    <el-card shadow="never" class="box-card">
      <div slot="header" style="display: flex; align-items: center; justify-content: space-between">
        <!--任务标题-->
        <span>{{ task.title }}</span>
        <!--甘特图时间刻度功能按钮-->
        <el-button-group>
          <!--          <el-button type="primary" size="mini" @click="handleReset"><i class="el-icon-refresh"></i></el-button>-->
          <el-button type="primary" size="mini" @click="handleZoomOut"><i class="el-icon-minus"></i></el-button>
          <el-button type="primary" size="mini" @click="handleZoomIn"><i class="el-icon-plus"></i></el-button>
        </el-button-group>
      </div>
      <!--任务甘特图组件-->
      <div ref="gantt" style="width: 100%; height:auto; position: relative;"></div>


      <!--任务功能按钮显示-->
      <div style="margin: 1.8725rem auto">
        <el-button type="primary" @click="decompose" size="mini" v-if="buttonVisibility.showDecompose">分 解</el-button>
        <el-button type="primary" @click="dialogTransmitVisible = true" size="mini"
                   v-if="buttonVisibility.showTransmit">转 交
        </el-button>
        <el-button type="primary" @click="dialogCompleteApplyVisible = true" size="mini"
                   v-if="buttonVisibility.showComplete">完 成
        </el-button>
        <el-button type="primary" v-if="taskHistoryCompleteVOS.length > 0" @click="dialogHistoryCompleteVisible = true"
                   size="mini">
          历史完成
        </el-button>
        <el-button type="primary" @click="dialogDelayVisible = true" size="mini"
                   v-if="buttonVisibility.showApplyDelay">
          申请延期
        </el-button>
        <el-button type="primary" v-if="task.taskHistoryDelayVOS.length > 0" @click="dialogHistoryDelayVisible = true"
                   size="mini">
          历史延期
        </el-button>
      </div>

      <el-descriptions :column="5" border :size="size" label-class-name="label-style">
        <el-descriptions-item label="发布人" content-class-name="content-style">
          {{ task.releaseBy }}
        </el-descriptions-item>
        <el-descriptions-item label="发布时间" content-class-name="content-style2">
          {{ task.createTime }}
        </el-descriptions-item>
        <el-descriptions-item label="项目号" content-class-name="content-style">
          {{ task.projectSn }}
        </el-descriptions-item>
        <el-descriptions-item label="汇报频率" content-class-name="content-style">
          {{ task.frequency }}
        </el-descriptions-item>
        <el-descriptions-item label="任务负责人" content-class-name="content-style">
          {{ task.reportBy }}
        </el-descriptions-item>
        <el-descriptions-item label="任务内容" label-class-name="label-style" content-class-name="content-style1" :span="3">
          <el-table :show-header="headerVisible" :size="size" :data="task.contentSummaries" empty-text=" "
                    style="margin: 0;">
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="contentSummary"></el-table-column>
          </el-table>
        </el-descriptions-item>
        <el-descriptions-item label="附件" label-class-name="label-style" content-class-name="content-style1" :span="2">
          <el-table :size="size" :data="task.releaseAttachments" :show-header="headerVisible" empty-text="无附件">
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="filePath">
              <template slot-scope="scope">
                <el-link :href="scope.row.filePath" target="_blank">{{ extractFileName(scope.row.filePath) }}</el-link>
              </template>
            </el-table-column>
          </el-table>
        </el-descriptions-item>
      </el-descriptions>
      <div class="container1" ref="container">
        <el-table size="mini" border :data="dataTable"
                  :style="{ minWidth: tableWidth + 'px' }"
                  class="table">
          <el-table-column v-for="(week, index) in weeks" :key="index" :label="week.label">
            <template #default="scope">
              <div :style="getBorderStyle(index)">
                <!--工作计划和完成情况标题-->
                <el-row
                    style="align-items: center; background-color: #f0f0f0; gap: 1.25rem; margin: 0; padding: 5px 0;">
                  <el-col :span="12">
                    工作计划
                  </el-col>
                  <el-col :span="12">
                    完成情况
                  </el-col>
                </el-row>
                <!--工作计划和完成情况表格所在行-->
                <el-row :gutter="20" style="align-items: flex-start; gap: 1.25rem; height: auto; ">
                  <el-col :span="12">
                    <el-table :data="week.taskPlanSummaries" size="mini" :show-header="false" empty-text=" ">
                      <el-table-column>
                        <template #default="scope">
                          <div :class="{'editable-cell': isEditable(index, 'taskPlan')}">
                            <el-input size="mini" :autosize="{ minRows: 1, maxRows: 4}"
                                      v-model="scope.row.taskPlan" :disabled="!isEditable(index, 'taskPlan')"
                                      placeholder="请输入计划内容"></el-input>
                          </div>
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-col>
                  <el-col :span="12">
                    <el-table :data="week.taskCompleteSummaries" size="mini" :show-header="false" empty-text=" ">
                      <el-table-column>
                        <template #default="scope">
                          <div :class="{'editable-cell': isEditable(index, 'taskComplete')}">
                            <el-input size="mini" :autosize="{ minRows: 1, maxRows: 4}"
                                      v-model="scope.row.taskComplete" :disabled="!isEditable(index, 'taskComplete')"
                                      placeholder="请输入任务完成情况"></el-input>
                          </div>
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-col>
                </el-row>
                <!--增删行按钮/附件按钮所在行-->
                <el-row v-show="userControl && (isEditable(index, 'taskPlan') || isEditable(index, 'taskComplete'))"
                        style="border-bottom: 1px solid #E4E7ED; padding: 0; margin: 0;">
                  <el-col :span="24"
                          style="display: flex; align-items: center; justify-content: left; gap: 1.25rem; padding-left: 1.25rem">
                    <el-button @click="addRow(week)" type="text" icon="el-icon-plus"></el-button>
                    <el-button @click="removeRow(week)" type="text" icon="el-icon-minus"></el-button>
                    <el-upload class="upload-demo"
                               :action="uploadAction" :with-credentials="true"
                               multiple ref="reportUpload"
                               :on-success="(response, file, fileList) => handleReportSuccess(response, file, fileList, index)"
                               :show-file-list="false">
                      <el-button type="text" icon="el-icon-paperclip"></el-button>
                    </el-upload>
                  </el-col>
                </el-row>
                <!--上传成功后端upLoad响应路径行-->
                <el-row v-show="userControl && (isEditable(index, 'taskPlan') || isEditable(index, 'taskComplete'))"
                        style="align-items: center;  padding: 0; margin: 0;">
                  <el-col :span="24" style="display: flex; gap: 0.625rem">
                    <el-tag
                        v-for="attachment in week.reportFileList"
                        :key="attachment.filePath"
                        closable size="mini"
                        @close="handleRemove(attachment,index)">
                      <el-link :href="attachment.filePath" target="_blank">{{
                          extractFileName(attachment.filePath)
                        }}
                      </el-link>
                    </el-tag>
                  </el-col>
                </el-row>
                <!--附件数据-->
                <el-row :gutter="20" style="margin: 0; padding:5px 0; border: 1px solid #E4E7ED"
                        v-if="week.reportAttachments.length > 0">
                  <el-col :span="24" style="color: #545454; display: flex; gap: 0.625rem">
                    <el-tag size="mini"
                            v-for="attachment in week.reportAttachments.filter(attachment => attachment.isSaved)"
                            :key="attachment.filePath">
                      <el-link :href="attachment.filePath" target="_blank">{{
                          extractFileName(attachment.filePath)
                        }}
                      </el-link>
                    </el-tag>
                  </el-col>
                </el-row>
                <!--协调标题-->
                <el-row
                    style="align-items: center; gap: 1.125rem; background-color: #f0f0f0; padding: 5px 0; margin: 0;">
                  <el-col :span="24">
                    需协调解决的问题
                  </el-col>
                </el-row>
                <!--协调表格所在行-->
                <el-row style="align-items: flex-start; gap: 1.125rem; height: auto; ">
                  <el-col>
                    <el-table :data="week.taskCoordinateSummaries" size="mini" :show-header="false" empty-text=" "
                              style="width: 100%">
                      <el-table-column>
                        <template #default="scope">
                          <div :class="{'editable-cell': isEditable(index, 'taskCoordinate')}">
                            <el-input size="mini" :autosize="{ minRows: 1, maxRows: 4}"
                                      v-model="scope.row.taskCoordinate"
                                      :disabled="!isEditable(index, 'taskCoordinate')"
                                      placeholder="请输入协调内容"></el-input>
                          </div>
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-col>
                </el-row>
                <!--协调增删行按钮所在行-->
                <el-row v-show="userControl && (isEditable(index, 'taskPlan') || isEditable(index, 'taskCoordinate'))"
                        style="align-items: center; gap: 1.125rem; border-bottom:1px solid  #E4E7ED; padding: 0; margin: 0;">
                  <el-col :span="24" style="display:flex; gap: 1.125rem">
                    <el-button @click="addRowForCoordination(week)" type="text" icon="el-icon-plus"></el-button>
                    <el-button @click="removeRowForCoordination(week)" type="text"
                               icon="el-icon-minus"></el-button>
                  </el-col>
                </el-row>
                <!--评论标题-->
                <el-row
                    style="align-items: center; gap: 1.25rem; background-color: #f0f0f0; padding: 5px 0; margin: 0;">
                  <el-col :span="24">
                    评论
                  </el-col>
                </el-row>
                <!--评论表格所在行-->
                <el-row :gutter="20" style="align-items: flex-start; gap: 1.125rem; height: auto;">
                  <el-col>
                    <el-table :data="week.taskCommentSummaries" size="mini" :show-header="false" empty-text=" "
                              style="width: 100%">
                      <el-table-column prop="commentContent" min-width="70%"></el-table-column>
                      <el-table-column prop="createBy" min-width="10%"></el-table-column>
                      <el-table-column prop="createTime" min-width="20%"></el-table-column>
                    </el-table>
                  </el-col>
                </el-row>
                <!--新增评论所在行-->
                <el-row
                    style="align-items: center; gap: 1.125rem; border-bottom:1px solid  #E4E7ED; padding: 0; margin: 0;">
                  <el-col :span="24" style="display:flex; gap: 1.125rem">
                    <el-button @click="addComment(week.id)" type="text" icon="el-icon-chat-line-round"></el-button>
                  </el-col>
                </el-row>
                <!--评论附件所在行-->
                <el-row :gutter="20" style="margin:0; padding:5px 0; border: 1px solid #e4e7ed"
                        v-if="week.commentAttachments.length > 0">
                  <el-col :span="24" style="color: #545454; display: flex; gap: 0.625rem">
                    <el-tag size="mini"
                            v-for="attachment in week.commentAttachments.filter(attachment => attachment.isSaved)"
                            :key="attachment.filePath">
                      <el-link :href="attachment.filePath" target="_blank">{{
                          extractFileName(attachment.filePath)
                        }}
                      </el-link>
                    </el-tag>
                  </el-col>
                </el-row>
                <!--新增评论对话框-->
                <el-dialog title="添加评论" :visible.sync="commentFormVisible" :center="true" :close-on-click-modal="false"
                           append-to-body style="margin-top:6.25rem">
                  <el-form :model="commentForm" size="small">
                    <el-form-item>
                      <el-input
                          type="textarea"
                          placeholder="评论全文，可@相关人员"
                          maxlength="256"
                          show-word-limit
                          v-model="commentForm.commentContent">
                      </el-input>
                    </el-form-item>
                    <el-form-item>
                      <el-upload
                          class="upload-demo" ref="commentUpload"
                          :action="uploadAction" :with-credentials="true"
                          :on-success="(response, file, fileList) => handleCommentSuccess(response, file, fileList, index)"
                          :on-remove="(file, fileList) => handleCommentRemove(file, fileList, index)"
                          :file-list="commentFileList">
                        <el-button type="text" icon="el-icon-paperclip"></el-button>
                      </el-upload>
                    </el-form-item>
                  </el-form>
                  <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="submitComment">确 定</el-button>
                  </div>
                </el-dialog>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div style="margin: 2rem auto">
        <el-button type="primary" @click="report" size="mini" v-if="buttonVisibility.showReport">提 交</el-button>
      </div>
    </el-card>
    <el-dialog title="任务完成申请" :center="true" :visible.sync="dialogCompleteApplyVisible" :close-on-click-modal="false"
               width="50%">
      <el-form :model="completeApplyForm" size="mini" label-position="left" label-width="6.25rem">
        <el-form-item label="完成情况">
          <el-input v-model="completeApplyForm.description" type="textarea" rows="3">
          </el-input>
        </el-form-item>
        <el-form-item label="附件">
          <el-upload
              class="upload-demo" :file-list="completeFileList" :with-credentials="true" ref="completeUpload"
              :action="uploadAction"
              :on-success="(response, file, fileList) => handleCompleteSuccess(response, file, fileList)"
              multiple :on-remove="handleCompleteRemove">
            <i class="el-icon-paperclip"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogCompleteApplyVisible = false" size="mini">取 消</el-button>
        <el-button type="primary" @click="completeApply" size="mini">确 认</el-button>
      </div>
    </el-dialog>
    <el-dialog title="任务转交" :center="true" :visible.sync="dialogTransmitVisible" :close-on-click-modal="false"
               width="20%">
      <el-form :model="transmitForm" size="mini" label-position="left">
        <el-form-item label="请选择" label-width="6.25rem">
          <el-cascader
              :options="optionsHeader"
              :props="{ expandTrigger: 'hover' }" @change="handleCascaderChange" size="mini">
          </el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogDelayVisible = false" size="mini">取 消</el-button>
        <el-button type="primary" @click="transmit" size="mini">确 认</el-button>
      </div>
    </el-dialog>
    <el-dialog title="任务延期申请" :center="true" :visible.sync="dialogDelayVisible" :close-on-click-modal="false">
      <el-form :model="delayForm" size="mini">
        <el-form-item label="延期理由" label-width="6.25rem">
          <el-input v-model="delayForm.delayReason"></el-input>
        </el-form-item>
        <el-form-item label="计划延期日期" label-width="6.25rem">
          <el-date-picker
              v-model="delayForm.delayProposedDate"
              type="date"
              placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogDelayVisible = false" size="mini">取 消</el-button>
        <el-button type="primary" @click="delay" size="mini">提 交</el-button>
      </div>
    </el-dialog>
    <el-dialog title="任务历史延期信息" :center="true" :visible.sync="dialogHistoryDelayVisible" :close-on-click-modal="false">
      <el-descriptions v-for="(item, index) in task.taskHistoryDelayVOS" :key="index" :column="4" border :size="size"
                       label-class-name="label-style" :title="`历史延期${index+1}`">
        <el-descriptions-item label="申请人" content-class-name="content-style">{{ item.applicant }}</el-descriptions-item>
        <el-descriptions-item label="原计划完成日期" content-class-name="content-style2">{{
            item.planDate
          }}
        </el-descriptions-item>
        <el-descriptions-item label="延期日期" content-class-name="content-style2">{{
            item.delayApprovedDate
          }}
        </el-descriptions-item>
        <el-descriptions-item label="延期时长" content-class-name="content-style">
          {{ calculateDelayDuration(item.planDate, item.delayApprovedDate) }}天
        </el-descriptions-item>
        <el-descriptions-item label="延期理由" content-class-name="content-style1" :span="4">{{
            item.delayReason
          }}
        </el-descriptions-item>
        <el-descriptions-item label="审批意见" content-class-name="content-style1" :span="4">{{
            item.approvalOpinion
          }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
    <el-dialog title="任务历史完成信息" :center="true" :visible.sync="dialogHistoryCompleteVisible"
               :close-on-click-modal="false">
      <el-descriptions v-for="(item, index) in taskHistoryCompleteVOS" :key="index" :column="3" border :size="size"
                       label-class-name="label-style"
                       :title="`历史完成申请${index+1}`">
        <el-descriptions-item label="申请人" content-class-name="content-style">{{ item.applicant }}</el-descriptions-item>
        <el-descriptions-item label="审批人" content-class-name="content-style">{{ item.approver }}</el-descriptions-item>
        <el-descriptions-item label="审批时间" content-class-name="content-style">{{
            item.approvalTime
          }}
        </el-descriptions-item>
        <el-descriptions-item label="完成情况" content-class-name="content-style1" :span="3">{{
            item.description
          }}
        </el-descriptions-item>
        <el-descriptions-item label="附件" content-class-name="content-style" :span="3">
          <el-tag v-for="attachment in item.taskAttachments" size="mini"
                  :key="attachment.filePath">
            <el-link :href="attachment.filePath" target="_blank">{{
                extractFileName(attachment.filePath)
              }}
            </el-link>
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="审批意见" content-class-name="content-style1" :span="3">{{
            item.approvalOpinion
          }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
    <el-dialog title="任务延期审批" :center="true" :visible.sync="dialogDelayApprovalVisible" :close-on-click-modal="false">
      <el-descriptions :column="4" border :size="size"
                       title="待审批延期">
        <el-descriptions-item label="申请人" content-class-name="content-style">{{
            latestTaskDelayApplyVO?.applicant
          }}
        </el-descriptions-item>
        <el-descriptions-item label="原计划完成日期" content-class-name="content-style2">{{ latestTaskDelayApplyVO?.planDate }}
        </el-descriptions-item>
        <el-descriptions-item label="申请延期日期" content-class-name="content-style2">{{
            latestTaskDelayApplyVO?.delayProposedDate
          }}
        </el-descriptions-item>
        <el-descriptions-item label="延期时长" content-class-name="content-style">
          {{ calculateDelayDuration(latestTaskDelayApplyVO?.planDate, latestTaskDelayApplyVO?.delayProposedDate) }}天
        </el-descriptions-item>
        <el-descriptions-item label="延期理由" content-class-name="content-style1" :span="4">{{
            latestTaskDelayApplyVO?.delayReason
          }}
        </el-descriptions-item>
        <el-descriptions-item label="审批意见" content-class-name="content-style1" :span="4">
          <el-input type="textarea"
                    placeholder="评论全文，可@相关人员" v-model="approvalOpinion"
                    maxlength="256"
                    show-word-limit size="mini">
          </el-input>
        </el-descriptions-item>
        <el-descriptions-item>
          <el-button type="text">退 回</el-button>
          <el-button type="text" @click="approvedDelay" :disabled="!this.buttonVisibility.showLatestApplyDelay">同 意
          </el-button>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
    <el-dialog title="任务完成审批" :center="true" :visible.sync="dialogCompleteApprovalVisible"
               :close-on-click-modal="false">
      <el-descriptions :column="2" border :size="size"
                       title="待审批的完成申请" label-class-name="label-style">
        <el-descriptions-item label="申请人" content-class-name="content-style1">{{
            latestTaskCompleteApplyVO?.applicant
          }}
        </el-descriptions-item>
        <el-descriptions-item label="提交时间" content-class-name="content-style1">{{
            latestTaskCompleteApplyVO?.createTime
          }}
        </el-descriptions-item>
        <el-descriptions-item label="完成情况" :span="2">{{ latestTaskCompleteApplyVO?.description }}
        </el-descriptions-item>
        <el-descriptions-item label="附件" :span="2">
          <el-tag v-for="attachment in latestTaskCompleteApplyVO?.taskAttachments" size="mini"
                  :key="attachment.filePath">
            <el-link :href="attachment.filePath" target="_blank">{{
                extractFileName(attachment.filePath)
              }}
            </el-link>
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="审批意见" content-class-name="content-style1" :span="3">
          <el-input type="textarea"
                    placeholder="评论全文，可@相关人员" v-model="completeApprovalOpinion"
                    maxlength="256"
                    show-word-limit size="mini">
          </el-input>
        </el-descriptions-item>
        <el-descriptions-item>
          <el-button type="text">退 回</el-button>
          <el-button type="text" @click="approvedComplete" :disabled="!this.buttonVisibility.showLatestApplyComplete">同
            意
          </el-button>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

  </div>
</template>

<script>
import {mapState} from 'vuex';
import gantt from "dhtmlx-gantt";
import {optionsHeader} from "@/utils/optionsHeader";
import "dhtmlx-gantt/codebase/dhtmlxgantt.css";

export default {
  name: "TaskToolTip",
  data() {
    return {
      currentTask: {},
      uploadAction: `${process.env.VUE_APP_API_BASE_URL}/file/upload`,
      dataTable: [{}],
      dialogDelayVisible: false,
      delayForm: {
        delayProposedDate: '',
        delayReason: '',
      },
      weeks: [{
        taskPlanSummaries: [],
        taskCompleteSummaries: [],
        taskCoordinateSummaries: [],
        taskCommentSummaries: [],
        reportAttachments: [],
        commentAttachments: []
      }],
      currentWeekIndex: -1,
      size: 'small',
      headerVisible: false,
      commentFileList: [],
      completeFileList: [],
      screenWidth: window.innerWidth, // 添加屏幕宽度变量
      commentFormVisible: false,
      commentForm: {commentContent: '', taskAttachments: ''},
      chooseWeekIndex: '',
      dialogKey: 0,
      selected_column: null,
      taskHistoryDelayVOS: [],
      taskHistoryCompleteVOS: [],
      latestTaskCompleteApplyVO: null,
      latestTaskDelayApplyVO: null,
      approvalOpinion: '',
      completeApprovalOpinion: '',
      dialogTransmitVisible: false,
      dialogCompleteApplyVisible: false,
      dialogHistoryDelayVisible: false,
      dialogHistoryCompleteVisible: false,
      dialogDelayApprovalVisible: false,
      dialogCompleteApprovalVisible: false,
      optionsHeader: optionsHeader,
      transmitForm: {
        reportBy: ''
      },
      completeApplyForm: {
        taskId: '',
        description: '',
        taskAttachments: [],
      }
    }
  },
  watch: {
    screenWidth(newWidth, oldWidth) {
      this.adjustTableWidth();
    },
    'task': {
      handler() {
        this.calculateWeeks();
      },
      deep: true,
      immediate: true // 确保组件加载时立即执行一次
    },
    'task.id': function (newVal, oldVal) {
      if (newVal !== oldVal) {
        this.showCompleteVO();
      }
    },
    'this.$store.state.ganttConfig': {
      handler(newConfig) {
        this.configureGantt() // 当配置变更时重新配置甘特图
        this.addTodayMarker()
      },
      deep: true
    },
    // 监听 selected_column 的变化
    selected_column(newDate, oldDate) {
      if (newDate !== oldDate) {
        const weekIndex = this.getWeekIndexByDate(newDate);
        this.chooseWeekIndex = weekIndex
        this.scrollToWeek(weekIndex);
      }
    },
  },
  computed: {
    ...mapState({
      task: state => state.currentTask
    }),

    displayedWeeks() {
      return this.weeks;
    },
    columnWidth() {
      const baseWidth = (this.screenWidth - 285) / Math.min(this.weeks.length, 3);
      return baseWidth;
    },
    tableWidth() {
      return this.columnWidth * this.weeks.length;
    },
    currentWeek() {
      return this.getWeekNumber(new Date());
    },
    buttonVisibility() {
      const user = JSON.parse(localStorage.getItem('user'));
      return {
        showReport: this.task.reportBy === user.nickName,//提交汇报按钮
        showDecompose: this.task.reportBy === user.nickName,//分解任务按钮
        showTransmit: this.task.reportBy === user.nickName,//转交任务按钮
        showComplete: this.task.reportBy === user.nickName,//完成任务按钮
        showApplyDelay: this.task.reportBy === user.nickName,//任务延期申请按钮
        showLatestApplyDelay: this.task.releaseBy === user.nickName,//待审批的延期申请
        showLatestApplyComplete: this.task.releaseBy === user.nickName,//待审批的完成申请
      };
    },
    userControl() {
      const user = JSON.parse(localStorage.getItem('user'))
      const currentUser = user.nickName
      return this.task.reportBy === currentUser;
    },

  },
  methods: {
    handleCascaderChange(value) {
      this.transmitForm.reportBy = value[value.length - 1];
    },
    convertUTCDateToLocalDate(date) {
      const localDate = new Date(date.getTime() + (date.getTimezoneOffset() * 60000));
      // 中国标准时间，UTC+8
      const offset = 8 * 60 * 60000;
      return new Date(localDate.getTime() + offset);
    },
    calculateWeeks() {
      const task = _.cloneDeep(this.task);
      if (task.latestTaskCompleteApplyVO) {
        this.latestTaskCompleteApplyVO = task.latestTaskCompleteApplyVO;
      }
      if (task.latestTaskDelayApplyVO) {
        this.latestTaskDelayApplyVO = task.latestTaskDelayApplyVO;
      }
      console.log("当前从VUEX中获取的生成周表格的任务是" + JSON.stringify(task, null, 2));

      let start = this.convertUTCDateToLocalDate(new Date(task.start_date));
      let end = this.convertUTCDateToLocalDate(new Date(task.end_date));
      let today = this.convertUTCDateToLocalDate(new Date());
      let current = new Date(start);
      this.weeks = [];
      let weekIndex = 0;
      let isFirstWeek = true;
      const formatDate = gantt.date.date_to_str("%Y/%m/%d");

      while (current <= end) {
        let weekStart = new Date(current);
        let weekEnd = new Date(weekStart);
        weekEnd.setDate(weekEnd.getDate() + 6);  // 通常设置为满一周
        if (isFirstWeek) {
          weekStart = new Date(start);
          weekEnd = new Date(start);
          weekEnd.setDate(weekEnd.getDate() + (7 - weekEnd.getDay()));  // 第一周可能不满
          isFirstWeek = false;
        }
        if (weekEnd > end) {
          weekEnd = new Date(end);  // 最后一周结束日期应该是任务的结束日期
        }
        let isCurrentWeek = (formatDate(today) >= formatDate(weekStart) && formatDate(today) <= formatDate(weekEnd));
        if (isCurrentWeek) {
          this.currentWeekIndex = weekIndex;
        }
        let label = `第${weekIndex + 1}周 (${weekStart.toLocaleDateString()} - ${weekEnd.toLocaleDateString()})`;
        let weekData = {
          id: weekIndex,
          label: label,
          isCurrentWeek: isCurrentWeek,
          weekStart: weekStart,
          weekEnd: weekEnd,
          taskPlanSummaries: task.taskPlanSummaries.filter(item => item.weekLabel === weekIndex + 1),
          taskCompleteSummaries: task.taskCompleteSummaries.filter(item => item.weekLabel === weekIndex + 1),
          taskCoordinateSummaries: task.taskCoordinateSummaries.filter(item => item.weekLabel === weekIndex + 1),
          taskCommentSummaries: task.taskCommentSummaries.filter(item => item.weekLabel === weekIndex + 1),
          reportAttachments: task.reportAttachments.filter(item => item.weekLabel === weekIndex + 1),
          commentAttachments: task.commentAttachments.filter(item => item.weekLabel === weekIndex + 1),
          reportFileList: []
        };
        this.$set(this.weeks, weekIndex, weekData);
        weekIndex++;
        current = new Date(weekEnd);
        current.setDate(current.getDate() + 1);
      }
      console.log("weeks数组:", this.weeks);
    },
    getWeekNumber(date) {
      const firstDayOfYear = new Date(date.getFullYear(), 0, 1);
      const pastDaysOfYear = (date - firstDayOfYear) / 86400000; // 86400000 = 1000 * 60 * 60 * 24
      // 计算第一天是星期几（0-星期日，1-星期一，...，6-星期六）
      const firstDayOfWeek = firstDayOfYear.getDay();
      // 如果第一天是星期日，则假设周从星期一开始，第一天属于上一年的最后一周
      const weekNumber = Math.ceil((pastDaysOfYear + firstDayOfWeek) / 7);
      return weekNumber;
    },
    isEditable(weekIndex, type) {
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      const currentWeekIndex = this.getCurrentWeekIndex(today);

      switch (type) {
        case 'taskPlan':
        case 'taskCoordinate':
          // 下周的计划和协调内容可编辑
          return weekIndex === currentWeekIndex + 1;
        case 'taskComplete':
          // 当前周的完成情况可编辑
          return weekIndex === currentWeekIndex;
        default:
          return false;
      }
    },
    getCurrentWeekIndex(today) {
      // 首先将 UTC 时间转换为本地时间
      const start = this.convertUTCDateToLocalDate(new Date(this.task.start_date));
      start.setHours(0, 0, 0, 0);
      let weekStart = new Date(start);
      weekStart.setDate(weekStart.getDate() - (weekStart.getDay() || 7) + 1); // 调整到周一
      let weekIndex = 0;

      // 确保今天的日期也是本地时间
      today = this.convertUTCDateToLocalDate(today);
      today.setHours(0, 0, 0, 0);

      while (weekStart <= today) {
        if (today < new Date(weekStart.getTime() + 7 * 24 * 60 * 60 * 1000)) {
          return weekIndex;
        }
        weekStart.setDate(weekStart.getDate() + 7);
        weekIndex++;
      }

      return weekIndex; // 如果今天日期超出任务结束日期，返回最后一周
    },
    initGantt() {
      const task = this.task;
      // 直接在这里进行 HTTP 请求获取子任务数据
      this.$http.get("task/subTask/" + task.id)
          .then((response) => {
            let tasksData
            if (response.data.code == 1) {
              const subTask = response.data.data;
              tasksData = this.prepareTasksData(task, subTask);
            } else {
              tasksData = this.prepareTasksData(task, []);
              alert("没有子任务数据");
            }
            gantt.init(this.$refs.gantt);
            gantt.clearAll();
            console.log("渲染前的任务数据" + JSON.stringify(tasksData, null, 2))
            gantt.parse({data: tasksData});
            gantt.render();
            this.handleGanttRender();
            this.addTodayMarker();

          })
      this.configureGantt();
      this.setupTemplates();
      this.attachTaskClickEvent()
      this.attachScaleClickEvent()
    },
    handleGanttRender() {
      gantt.attachEvent("onGanttRender", () => {
        /*        console.log("handleGanttRender方法执行了")*/
        gantt.eachTask((task) => {
          // 使用 gantt.getTask(task.id).start_date 和 gantt.getTask(task.id).end_date 来获取任务的开始和结束日期
          const start = gantt.getTask(task.id).start_date;
          const end = gantt.getTask(task.id).end_date;
          const taskContent = this.task_text_template(start, end, task);
          const taskRow = gantt.getTaskNode(task.id);
          if (taskRow) {
            // 假设任务内容显示在第一个子元素中，你可能需要根据实际情况修改
            const taskContentElement = taskRow.children[1];
            if (taskContentElement) {
              taskContentElement.innerHTML = taskContent;
            }
          }
        });
      });
    },
    task_text_template: function (start, end, task) {
      let content = `<div>${task.statusName}</div>`;
      if (task.taskMilestones && task.taskMilestones.length > 0) {
        let scale = gantt.getScale();
        if (!scale || !scale.trace_x) {
          console.error("Scale data is not available.");
          return content; // 提前返回，避免进一步的错误
        }
        const taskStartDate = new Date(task.start_date);
        const taskStartPos = this.calculateDatePos(scale, taskStartDate);

        task.taskMilestones.forEach(milestone => {
          const milestoneTime = new Date(milestone.time);
          const milestonePos = this.calculateDatePos(scale, milestoneTime);

          if (milestonePos !== -1 && taskStartPos !== -1) {
            const taskRow = gantt.getTaskNode(task.id);
            if (taskRow) {
              const milestoneElement = this.createMilestoneElement(milestone, milestonePos, taskStartPos);
              taskRow.appendChild(milestoneElement);
            }
          }
        });
      }
      return content;
    },

    createMilestoneElement(milestone, milestonePos, taskStartPos) {
      console.log("taskStart的值：" + taskStartPos);
      const milestoneTime = new Date(milestone.time);
      const milestoneElement = document.createElement('div');
      milestoneElement.className = 'custom-milestone';
      // 调整position，使其相对于任务条的实际位置
      const adjustedPosition = milestonePos - taskStartPos;
      milestoneElement.style.cssText = `left: ${adjustedPosition}px; top: 50%; transform: translateY(-50%)`;
      const iconElement = document.createElement('i');
      iconElement.className = 'el-icon-s-flag';
      iconElement.title = `里程碑: ${milestone.name} 日期： ${gantt.date.date_to_str(gantt.config.xml_date)(milestoneTime)}`;
      milestoneElement.appendChild(iconElement);
      return milestoneElement;
    },
    calculateDatePos(scale, date) {
      for (let i = 0; i < scale.trace_x.length; i++) {
        const currentDate = new Date(scale.trace_x[i]);
        const nextDate = i + 1 < scale.trace_x.length ? new Date(scale.trace_x[i + 1]) : null;

        if ((!nextDate || date < nextDate) && date >= currentDate) {
          const cellStartPos = scale.left[i];
          const cellWidth = scale.width[i];
          const timeRange = nextDate ? (nextDate - currentDate) : (7 * 24 * 60 * 60 * 1000); // 假设周为7天
          const elapsedTime = date - currentDate;
          const relativePos = (elapsedTime / timeRange) * cellWidth;

          return cellStartPos + relativePos;
        }
      }
      return -1;
    },
    handleZoomOut() {
      this.$store.dispatch('zoomOut').then(() => {
        this.handleGanttRender()
      });
    },
    handleZoomIn() {
      this.$store.dispatch('zoomIn').then(() => {
        this.handleGanttRender()
      });
    },

    prepareTasksData(task, subTasks) {
      // 主任务数据
      const mainTaskData = {
        id: task.id,
        sn: task.sn,
        text: task.text,
        start_date: gantt.date.date_to_str(gantt.config.xml_date)(new Date(task.start_date)),
        end_date: gantt.date.date_to_str(gantt.config.xml_date)(new Date(task.end_date)),
        duration: task.duration,
        color: this.getColorByStatus(task.statusName),
        progress: task.progress,
        projectSn: task.projectSn,
        reportBy: task.reportBy,
        releaseBy: task.releaseBy,
        statusName: task.statusName,
        categoryName: task.categoryName,
        latestTaskCompleteApplyVO: task.latestTaskCompleteApplyVO,
        latestTaskDelayApplyVO: task.latestTaskDelayApplyVO,
        taskMilestones: task.taskMilestones.map(milestone => {
          return {
            ...milestone,
            time: new Date(milestone.time)
          }
        }),
        parent: 0  // 主任务的父级通常是0，表示顶级
      };
      // 子任务数据，确保每个子任务的parent属性正确设置为其在数据库中的parent_id
      const subTaskData = subTasks.map(item => {
        const startDate = Date.parse(new Date(item.startTime.replace(/-/g, "/")))
        const endDate = Date.parse(new Date(item.endTime.replace(/-/g, "/")))
        let EndDateForGantt
        if (item.actualFinishingTime) {
          EndDateForGantt = Date.parse(new Date(item.actualFinishingTime.replace(/-/g, "/")))
        } else if (item.delayApprovedDate) {
          EndDateForGantt = Date.parse(new Date(item.delayApprovedDate.replace(/-/g, "/")))
        } else {
          EndDateForGantt = Date.parse(new Date(item.endTime.replace(/-/g, "/")))
        }
        const originalDuration = Math.floor((endDate - startDate) / (24 * 3600 * 1000)) + 1
        const totalDuration = Math.floor((EndDateForGantt - startDate) / (24 * 3600 * 1000)) + 1
        const progress = originalDuration / totalDuration
        return {
          id: item.id,
          sn: item.sn,
          text: item.title,
          start_date: gantt.date.date_to_str(gantt.config.xml_date)(new Date(item.startTime)),
          duration: totalDuration,
          color: this.getColorByStatus(item.statusName),
          progress: progress,
          reportBy: item.reportBy,
          statusName: item.statusName,
          categoryName: item.categoryName,
          latestTaskCompleteApplyVO: item.latestTaskCompleteApplyVO,
          latestTaskDelayApplyVO: item.latestTaskDelayApplyVO,
          taskMilestones: item.taskMilestones.map(milestone => {
            return {
              ...milestone,
              time: new Date(milestone.time)
            }
          }),
          parent: item.parentId
        }
        // 使用后端提供的parentId确保层级正确
      });
      return [mainTaskData, ...subTaskData];
    },
    getColorByStatus(statusName) {
      switch (statusName) {
        case '进行中':
          return "rgba(76,175,80,0.7)"; // 浅绿色
        case '已完成':
          return "rgba(211,212,211,0.8)"; // 灰色
        case '已延期':
          return "rgba(200,186,93,0.8)"; // 橙色
        default:
          return "rgba(0,0,0,0.5)"
      }
    },
    attachTaskClickEvent() {
      if (this.taskClickEventId) {
        gantt.detachEvent(this.taskClickEventId);
      }
      this.taskClickEventId = gantt.attachEvent("onTaskClick", (id, e) => {
        const task = gantt.getTask(id);
        console.log("点击事件选择的任务数据：" + JSON.stringify(task, null, 2))
        // Check if the click target is a span
        const isSpanClick = e.target.tagName === 'SPAN';
        if (isSpanClick) {
          this.$http.get("/task/detail/" + task.id).then(response => {
            if (response.data.code == 1) {
              const updatedTask = {
                ...response.data.data,
                categoryName: response.data.data.categoryName,
                statusName: task.statusName,
                start_date: gantt.date.date_to_str(gantt.config.xml_date)(new Date(response.data.data.startTime)),
                end_date: gantt.date.date_to_str(gantt.config.xml_date)(new Date(response.data.data.delayApprovedDate || response.data.data.endTime)),
                latestTaskCompleteApplyVO: task.latestTaskCompleteApplyVO,
                latestTaskDelayApplyVO: task.latestTaskDelayApplyVO
              };
              this.dialogKey++;
              this.$store.dispatch("updateCurrentTask", updatedTask);
            }
          });
          if (e.target.classList.contains('complete-badge')) {
            this.dialogCompleteApprovalVisible = true;
          } else if (e.target.classList.contains('delay-badge')) {
            this.dialogDelayApprovalVisible = true;
          }
          return true;
        }
        if (task) {
          this.$http.get("/task/detail/" + task.id).then(response => {
            if (response.data.code == 1) {
              const updatedTask = {
                ...response.data.data,
                categoryName: response.data.data.categoryName,
                statusName: task.statusName,
                start_date: gantt.date.date_to_str(gantt.config.xml_date)(new Date(response.data.data.startTime)),
                end_date: gantt.date.date_to_str(gantt.config.xml_date)(new Date(response.data.data.delayApprovedDate || response.data.data.endTime)),
                latestTaskCompleteApplyVO: task.latestTaskCompleteApplyVO,
                latestTaskDelayApplyVO: task.latestTaskDelayApplyVO,
              };
              this.renderTaskRow(task.id);
              this.dialogKey++;
              this.$store.dispatch("updateCurrentTask", updatedTask);
            }
          });
          const today = new Date()
          const currentWeekIndex = this.getCurrentWeekIndex(today)
          this.$nextTick(() => {
            this.scrollToWeek(currentWeekIndex);
            console.log("滚动尝试执行");
          });
        }
        return true;
      });
    },
    renderTaskRow(taskId) {
      const task = gantt.getTask(taskId);
      if (task) {
        const taskRow = gantt.getTaskNode(taskId);
        if (taskRow) {
          taskRow.innerHTML = ''; // 清空内容
          const start = gantt.getTask(taskId).start_date;
          const end = gantt.getTask(taskId).end_date;
          const taskContent = this.task_text_template(start, end, task);
          // 假设任务内容显示在第一个子元素中，你可能需要根据实际情况修改
          const taskContentElement = document.createElement('div');
          taskContentElement.innerHTML = taskContent;
          taskRow.appendChild(taskContentElement);
        }
      }
    },

    attachScaleClickEvent() {
      this.scaleClickEventId = gantt.attachEvent("onScaleClick", (e, date) => {
        this.selected_column = date
        console.log("选中的时间刻度是：" + this.selected_column);
        var pos = gantt.getScrollState();
        gantt.render()
        gantt.scrollTo(pos.x, pos.y);
        // 计算选定日期所在的周的索引
        const weekIndex = this.getWeekIndexByDate(date);
        // 触发滚动到周列表格中对应周的逻辑
        this.scrollToWeek(weekIndex);
      });
    },
    configureGantt() {
      const ganttConfig = this.$store.state.ganttConfig;
      gantt.i18n.setLocale(ganttConfig.locale);
      gantt.config.scale_height = ganttConfig.scale_height;
      gantt.config.scales = ganttConfig.scales;
      gantt.config.xml_date = ganttConfig.xml_date;
      gantt.config.row_height = ganttConfig.row_height;
      gantt.config.bar_height = ganttConfig.bar_height;
      gantt.config.show_markers = ganttConfig.show_markers;
      gantt.config.show_chart = true;
      gantt.config.autosize = ganttConfig.autosize;
      gantt.config.readonly = ganttConfig.readonly;
      gantt.config.show_grid = ganttConfig.show_grid;
      gantt.config.min_column_width = ganttConfig.min_column_width;
      gantt.config.show_progress = ganttConfig.show_progress;
      // 获取容器宽度
      const containerWidth = this.$refs.gantt.clientWidth; // 假设已经存在 gannt 组件的容器引用

      // 定义各列百分比（总和约100%）
      const columnPercents = {
        wbs: 0.02,
        text: 0.20,
        reportBy: 0.04,
        statusName: 0.02,
      };

      // 动态设置列宽
      gantt.config.columns = [
        {
          name: "wbs",
          label: "wbs",
          width: containerWidth * columnPercents.wbs,  // 根据容器宽度计算列宽
          align: 'left',
          template: gantt.getWBSCode,
        },
        {
          name: "text",
          label: "名称",
          width: containerWidth * columnPercents.text,  // 根据容器宽度计算列宽
          align: 'left',
          tree: true,
          template: (task) => {
            let badgeHtml = '';
            if (task.latestTaskCompleteApplyVO) {
              badgeHtml += `<span class="custom-badge complete-badge">1</span>`;
            }
            if (task.latestTaskDelayApplyVO) {
              badgeHtml += `<span class="custom-badge delay-badge">1</span>`;
            }
            return `<span class='title_column' title="${task.text}">${badgeHtml}${task.text}</span>`;
          },
        },
        {
          name: "reportBy",
          label: "负责人",
          width: containerWidth * columnPercents.reportBy,  // 根据容器宽度计算列宽
          align: 'center',
          template: function (task) {
            return task.reportBy;
          },
        },
        {
          name: "statusName",
          label: "状态",
          width: containerWidth * columnPercents.statusName,  // 根据容器宽度计算列宽
          align: 'center',
          template: function (task) {
            // 根据状态返回不同的图标
            let iconHtml = '';
            switch (task.statusName) {
              case '已完成':
                iconHtml = '<i class="el-icon-success" style="color: #BDBEBCEA; font-size: 0.75rem"></i>';
                break;
              case '进行中':
                iconHtml = '<i class="el-icon-circle-check" style="color: #189C05FF; font-size: 0.75rem"></i>';
                break;
              case '已延期':
                iconHtml = '<i class="el-icon-warning" style="color: #b29503; font-size: 0.75rem"></i>';
                break;
              default:
                iconHtml = '<i class="el-icon-question"></i>'; // 默认图标
            }
            return `<el-result>${iconHtml}</el-result>`; // 返回构造的 HTML 字符串，模拟 el-result 组件
          },
        },
      ];
      gantt.plugins({
        marker: true
      })
    },
    addTodayMarker() {
      var dateToStr = gantt.date.date_to_str(gantt.config.task_date);
      var today = new Date();
      var markerId = gantt.addMarker({
        start_date: today,
        css: "today_line",
        text: "今日",
        title: "今日" + dateToStr(today)
      });
      gantt.renderMarkers(); // 确保标记被渲染
      return markerId;
    },
    is_selected_column(column_date) {
      return this.selected_column && column_date.valueOf() === this.selected_column.valueOf();
    },
    setupTemplates() {
      gantt.templates.scale_cell_class = (date) => {
        if (this.is_selected_column(date)) {
          return "highlighted-column";  // 应用高亮样式
        }
      };
      gantt.templates.timeline_cell_class = (item, date) => {
        if (this.is_selected_column(date)) {
          return "highlighted-column";
        }
      };
    },
    /*    handleReset() {
          this.$store.dispatch('resetGanttConfig').then(() => {
            this.updateMilestonePositions();
          });
        },*/
    scrollToWeek(weekIndex) {
      console.log("滚动方法执行了")
      console.log(weekIndex)
      const columnWidth = this.columnWidth; // 使用计算属性获取当前列宽
      /*
            console.log("columnWidth的值：", columnWidth)
      */
      const container = this.$refs.container;
      const scrollPosition = weekIndex * columnWidth;
      /*      console.log("scrollPosition的值：", scrollPosition)
            console.log("container.offsetWidth的值：", container.offsetWidth)*/
      const a = scrollPosition - (container.offsetWidth / 2) + (columnWidth / 2);
      /*      console.log("a的值：", a)
            console.log("容器的总内容宽度：", container.scrollWidth);*/
      // 添加模糊效果
      container.classList.add('blurred');
      container.scrollLeft = a; // 将选中的列尽量置于容器中心
      /*      console.log("新的滚动位置：", container.scrollLeft);*/
      // 模拟滚动结束后移除模糊效果
      setTimeout(() => {
        container.classList.remove('blurred');
        /*        console.log("滚动结束，模糊效果已移除");*/
      }, 300); // 假设滚动动画持续时间为500毫秒
    },
    getWeekIndexByDate(date) {
      // 示例实现，根据实际情况调整
      return this.weeks.findIndex(week => date >= new Date(week.weekStart) && date <= new Date(week.weekEnd));
    },
    adjustTableWidth() {
      this.screenWidth = window.innerWidth; // 更新屏幕宽度
    },
    addRow(week) {
      week.taskPlanSummaries.push({taskPlan: ''});
      week.taskCompleteSummaries.push({taskComplete: ''});
    },
    removeRow(week) {
      week.taskPlanSummaries.pop();
      week.taskCompleteSummaries.pop();
    },
    addRowForCoordination(week) {
      week.taskCoordinateSummaries.push({taskCoordinate: ''});
    },
    removeRowForCoordination(week) {
      week.taskCoordinateSummaries.pop();
    },
    handleReportSuccess(response, file, fileList, index) {
      console.log(response.data)
      const attachment = {
        name: file.name,
        filePath: response.data,
        source: '汇报时',
        weekLabel: index + 1,
        isSaved: false
      }
      this.weeks[index].reportAttachments.push(attachment)
      this.weeks[index].reportFileList.push(attachment)
    },
    handleRemove(attachment, weekIndex) {
      this.$confirm('确定要删除这个文件吗?', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = this.weeks[weekIndex].reportFileList.findIndex(item => item.filePath === attachment.filePath);
        if (index !== -1) {
          this.weeks[weekIndex].reportFileList.splice(index, 1);
        }
      }).catch(() => {
        // 用户取消删除操作
        this.$message({
          type: 'info',
          message: '删除取消'
        });
      });
    },
    handleCommentSuccess(response, file, fileList, index) {
      console.log(response.data)
      const attachment = {
        name: file.name,
        filePath: response.data,
        source: '评论时',
        weekLabel: index,
        isSaved: false
      }
      this.weeks[index].commentAttachments.push(attachment)
      this.commentFileList.push(attachment)
    },
    handleCommentRemove(file, fileList, index) {
      console.log(file)
      const week = this.weeks[index];
      week.commentFileList = fileList;
      const removedFilePath = file.filePath;
      week.commentAttachments = week.commentAttachments.filter(
          att => att.filePath !== removedFilePath
      );
      console.log("文件已删除:", removedFilePath);
      console.log("当前附件列表:", week.commentAttachments);
    },
    handleCompleteSuccess(response, file, fileList) {
      console.log(response.data)
      const attachment = {
        filePath: response.data,
        source: '完成申请时'
      }
      this.completeApplyForm.taskAttachments.push(attachment)
    },
    handleCompleteRemove(file, fileList) {
      console.log(file)
      // 删除文件时需要从附件数组中移除
      const removedFilePath = file.response ? file.response.data : file.url;
      // 过滤掉已删除的文件
      this.completeApplyForm.taskAttachments = this.completeApplyForm.taskAttachments.filter(attachment => attachment.filePath !== removedFilePath);
      console.log("文件已删除:", removedFilePath);
      console.log("当前附件列表:", this.completeApplyForm.taskAttachments);
    },
    decompose() {
      this.$router.push("/sub_task")
    },
    transmit() {
      const taskTransmitDTO = {
        ...this.transmitForm,
        processInstanceId: this.task.processInstanceId,
        id: this.task.id
      }
      this.$http.post("/task/transmit/", taskTransmitDTO).then((response) => {
        if (response.data.code == 1) {
          this.$message.success("转交已完成")
          this.dialogTransmitVisible = false
        }
      })
    },
    showCompleteVO() {
      this.$nextTick(() => {
        this.$http.get(`/task/allComplete/${this.task.id}`).then((response) => {
          if (response.data.code == 1) {
            this.taskHistoryCompleteVOS = response.data.data;
            console.log(`任务完成申请历史信息：${JSON.stringify(this.taskHistoryCompleteVOS, null, 2)} `)
          } else {
            this.taskHistoryCompleteVOS = null; // 确保数据获取失败时，taskHistoryCompleteVOS为null
            console.error("无任务完成申请历史信息");
          }
        });
      })
    },
    completeApply() {
      this.completeApplyForm.taskId = this.task.id
      console.log(JSON.stringify(this.completeApplyForm, null, 2))
      this.$http.post("/task/completeApply", this.completeApplyForm).then((response) => {
        if (response.data.code == 1) {
          this.$message({type: "success", showClose: true, message: "已提交申请"})
          this.dialogCompleteApplyVisible = false
        } else {
          this.$message({type: "error", showClose: true, message: "提交失败"})
        }
      })
    },
    approvedComplete() {
      const ApprovedCompleteDTO = {
        processInstanceId: this.task.processInstanceId,
        categoryName: this.task.categoryName,
        actualFinishingTime: gantt.date.date_to_str(gantt.config.xml_date)(new Date()),
        taskId: this.task.id,
        approvalOpinion: this.completeApprovalOpinion
      }
      console.log(JSON.stringify(ApprovedCompleteDTO, null, 2))
      this.$http.post("/task/complete_apply/review/", ApprovedCompleteDTO).then((response) => {
        if (response.data.code == 1) {
          this.$message({type: "success", showClose: true, message: "任务已完成"})
        } else {
          this.$message({type: "error", showClose: true, message: "提交失败"})
        }
        this.dialogCompleteApprovalVisible = false
      })
    },
    delay() {
      const taskDelayDTO = {
        ...this.delayForm,
        delayProposedDate: gantt.date.date_to_str(gantt.config.xml_date)(new Date(this.delayForm.delayProposedDate)),
        title: this.task.title,
        projectSn: this.task.projectSn,
        taskId: this.task.id,
        applicant: this.task.reportBy,
        approver: this.task.releaseBy,
        planDate: gantt.date.date_to_str(gantt.config.xml_date)(new Date(this.task.end_date)),
        processInstanceId: this.task.processInstanceId
      }
      this.$http.post("/task/delay", taskDelayDTO).then((response) => {
        console.log(taskDelayDTO)
        if (response.data.code == 1) {
          this.$message({type: "success", showClose: true, message: "提交成功"})
        } else {
          this.$message({type: "error", showClose: true, message: "提交失败"})
        }
      })
      this.dialogDelayVisible = false
    },
    report() {
      console.log(this.currentWeekIndex)
      const editableData = {
        taskId: this.task.id,
        processInstanceId: this.task.processInstanceId,
        taskPlanSummaries: [],
        taskCompleteSummaries: [],
        taskCoordinateSummaries: [],
        taskAttachments: []
      };
      this.weeks.forEach(week => {
        week.reportAttachments.forEach(attachment => {
          if (!attachment.isSaved) {
            editableData.taskAttachments.push({
              filePath: attachment.filePath,
              source: attachment.source,
              weekLabel: attachment.weekLabel
            });
          }
        });
      });
      if (this.weeks[this.currentWeekIndex]) {
        // 完成情况
        editableData.taskCompleteSummaries = this.weeks[this.currentWeekIndex].taskCompleteSummaries.map(item => ({
          ...item,
          weekLabel: this.currentWeekIndex + 1,
          id: item.id
        }));
      }
      // 只添加下一周的计划和协调
      if (this.weeks[this.currentWeekIndex + 1]) {
        editableData.taskPlanSummaries = this.weeks[this.currentWeekIndex + 1].taskPlanSummaries.map(item => ({
          ...item,
          weekLabel: this.currentWeekIndex + 2,
          id: item.id
        }));
        editableData.taskCoordinateSummaries = this.weeks[this.currentWeekIndex + 1].taskCoordinateSummaries.map(item => ({
          ...item,
          weekLabel: this.currentWeekIndex + 2,
          id: item.id
        }));
      }
      // 发送数据到后端
      this.$http.post("/task/reportTask", editableData).then((response) => {
        console.log(JSON.stringify(editableData, null, 2))
        if (response.data.code == 1) {
          this.$message({type: "success", showClose: true, message: "提交成功"})
          this.reportFileList = []
          this.$router.push('/task');
        } else {
          this.$message({type: "error", showClose: true, message: "提交失败"})
        }
      })
    },
    addComment(weekId) {
      this.chooseWeekIndex = weekId
      this.commentFormVisible = true
    },
    submitComment() {
      const taskComment = {
        ...this.commentForm,
        taskId: this.task.id,
        weekLabel: this.chooseWeekIndex,
        taskAttachments: []
      }
      this.weeks.forEach(week => {
        week.commentAttachments.forEach(attachment => {
          if (!attachment.isSaved) {
            taskComment.taskAttachments.push({
              filePath: attachment.filePath,
              source: attachment.source,
              weekLabel: attachment.weekLabel
            });
          }
        });
      });
      console.log(taskComment)
      this.$http.post("/task/comment", taskComment).then((response) => {
        console.log(response.data)
        if (response.data.code == 1) {
          this.$message({type: "success", showClose: true, message: "提交成功"})
          this.commentFileList = []
        } else {
          this.$message({type: "error", showClose: true, message: "提交失败"})
        }
      })
      this.commentFormVisible = false
    },
    save() {
    },
    calculateDelayDuration(planDate, delayDate) {
      if (!planDate || !delayDate) return 0;
      const plan = new Date(planDate);
      const delay = new Date(delayDate);
      const timeDiff = delay - plan;
      const dayDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
      return dayDiff;
    },
    approvedDelay() {
      const approvedDelayDTO = {
        id: this.task.latestTaskDelayApplyVO.id,
        processInstanceId: this.task.processInstanceId,
        delayProposedDate: this.task.latestTaskDelayApplyVO.delayProposedDate,
        approvalOpinion: this.approvalOpinion
      }
      this.$http.post("/task/delay/approval/", approvedDelayDTO).then((response) => {
        if (response.data.code == 1) {
          this.$message({type: "success", showClose: true, message: "审批完成"})
        } else {
          this.$message({type: "error", showClose: true, message: "审批失败，请联系管理员"})
        }
        this.dialogDelayApprovalVisible = false
      })
    },
    getBorderStyle(index) {
      return {
        borderTop: this.chooseWeekIndex === index ? '1px solid rgba(245,108,108)' : 'none'
      };
    },
    extractFileName(path) {
      return path.substring(path.lastIndexOf('/') + 1);
    }
  },
  mounted() {
    this.initGantt();
    this.calculateWeeks();
    this.adjustTableWidth();
    this.showCompleteVO();
    window.addEventListener('resize', this.adjustTableWidth);
    const today = new Date()
    const currentWeekIndex = this.getCurrentWeekIndex(today)
    this.$nextTick(() => {
      this.scrollToWeek(currentWeekIndex);
      console.log("滚动尝试执行");
    });
  },
  beforeDestroy() {
    /*    this.$store.commit('RESET_CURRENT_TASK');*/
    window.removeEventListener('resize', this.adjustTableWidth);
    // 解绑 Gantt 图的事件
    if (this.taskClickEventId) {
      gantt.detachEvent(this.taskClickEventId);
      this.taskClickEventId = null; // 清除事件ID引用，确保完全解绑
    }
    if (this.scaleClickEventId) {
      gantt.detachEvent(this.scaleClickEventId);
      this.scaleClickEventId = null; // 清除事件ID引用，确保完全解绑
    }
  }
}
</script>
<style scoped>
::v-deep .container1 {
  overflow-x: auto;
  scroll-behavior: smooth; /* 确保滚动行为平滑 */
  width: 100%;
  border: 1px solid #ccc;
  overflow-y: hidden !important;
  margin-bottom: 2rem;
  border-collapse: collapse;
  box-sizing: border-box;
}

::v-deep .container1.blurred {
  transition: filter 0.3s ease-out;
  filter: blur(4px);
}


/* 修改表格行悬停的背景颜色 */
::v-deep .el-table .el-table__body tr:hover td {
  background-color: transparent !important;
}

/* 修改单元格的样式 */
.el-table ::v-deep .cell,
.el-table ::v-deep .el-table__cell {
  padding: 0 !important;
  text-align: start;
  vertical-align: top !important;
  margin: 0 !important;
  box-sizing: border-box;
}


/* 特定表格添加边框 */
::v-deep .el-table.table {
  border: none;
  border-collapse: collapse !important;
  width: 100%;
  margin: 0 auto;
  height: auto;
  overflow-y: hidden !important;
}

::v-deep .el-table.table tr td {
  border-right: 1px solid #ccc;
  border-collapse: separate !important;
  border-spacing: 0 !important;
}

::v-deep .el-table .el-table tr td {
  border: none !important;
  border-bottom: 1px solid #ccc !important;
  border-collapse: separate !important;
  border-spacing: 0 !important;
  text-align: center;
  height: 100%; /* 确保单元格高度充满，以便垂直居中 */
}

::v-deep .editable-cell {
  border-bottom: 1px solid #409EFF !important;
}

/* 这个是自定义列文本样式 */
::v-deep .gantt_grid_data .gantt_cell {
  font-size: 0.75rem;
  color: #606266; /* 设置字体大小 */
  padding: 0 0.5rem !important;
}

/* 为动态生成的表头单元格设置边框 */
::v-deep .el-table.table .el-table__header-wrapper .el-table__cell {
  border: 1px solid #ccc !important;
  border-top: none !important;
  border-left: none !important;
}

/* 确保表头单元格的边框不叠加 */
::v-deep .el-table.table .el-table__header-wrapper {
  border-collapse: separate !important;
  border-spacing: 0 !important;
}

/* 调整表头单元格的右边框，避免叠加 */
::v-deep .el-table.table .el-table__header-wrapper .el-table__cell:not(:last-child) {
  border-right: 1px solid #ccc !important;
}

/* 为内部 el-table 设置边框 */
::v-deep .el-table.table .el-table__body-wrapper .el-table {
  border: none !important;
  border-collapse: separate !important;
  border-spacing: 0 !important;
}

::v-deep .table .el-table .el-input__inner {
  border: none !important;
  box-shadow: none !important;
}

::v-deep .complete-badge {
  background-color: green;
}

::v-deep .delay-badge {
  background-color: #e85e5e;
}

::v-deep .gantt_task_line {
  top: -30px !important;
}

::v-deep .gantt_grid_head_cell {
  color: #909399;
  font-size: 0.75rem !important;
  font-family: "Helvetica Neue", "Helvetica" !important;
  font-weight: bold !important;
}

::v-deep .gantt_tree_content, .gantt_tree_icon {
  height: 100%;
  display: block;
  color: #909399;
  font-family: "Helvetica Neue", "Helvetica" !important;
  font-size: 0.75rem !important;
}

::v-deep .custom-badge {
  display: inline-block;
  padding: 0.1875rem 0.3125rem;
  border-radius: 50%; /* 将边框半径设置为50%，实现圆形外观 */
  color: white;
  font-size: 0.625rem;
  text-align: center; /* 让数字在圆形内居中显示 */
  line-height: 1; /* 根据实际情况调整行高，使数字垂直居中效果更好 */
  margin-right: 0.3125rem;
}

::v-deep .gantt_cell.gantt_cell_tree {
  padding: 0 !important;
}

::v-deep .label-style {
  width: 8%;
  color: #909399;
  font-size: 0.8125rem;
  font-weight: bold;
}

::v-deep .content-style1 {
  width: 20%;
  font-size: 0.75rem;
  word-break: break-all
}

::v-deep .content-style2 {
  width: 15%;
  font-size: 0.75rem;
  word-break: break-all;
}

::v-deep .content-style {
  width: 8%;
  font-size: 0.75rem;
  word-break: break-all
}
</style>


